const fs = require('fs');
const readline = require('readline');
const translate = require('@vitalets/google-translate-api');
const axios = require('axios')
const ProgressBar = require('progress');

const filePath = './data.txt'; // 输入文件的路径
const outputPath = './output.json'; // 输出JSON文件的路径

// 创建进度条
const progressBar = new ProgressBar('翻译进度 [:bar] :percent :etas', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: 0 // 我们稍后会设置总数
});

// 初始化JSON结构
let jsonOutput = {};

// 延迟函数
function delay(duration) {
    return new Promise(resolve => setTimeout(resolve, duration));
}

async function translate_baidu(text) {
    var data = {
        from: "en",
        to: "zh",
        q: text
    };

    var config = {
        method: 'post',
        url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=24.8c0a3bba3cfc19edf32c31d3aa15fdb1.2592000.1707327005.282335-46686141',
        data: data
    };
    try {
        const response = await axios(config)
        return response.data.result.trans_result[0].dst ?? null;
    } catch (error) {
        console.log(error);
        return null; // Optionally, you can return error details or a custom error message.
    }
}

async function processLine(line) {
    const parts = line.split('.');
    let currentLevel = jsonOutput;

    for (let i = 0; i < parts.length; i++) {
        const part = parts[i];
        const ba = await translate_baidu(part)
        console.log(part + "=>" + ba);
        if (!currentLevel[part]) {
            currentLevel[part] = i === parts.length - 1 ? { key: line } : { name: "", sound: { name: "" } };
            console.log(currentLevel[part]);
        }
        if (i === parts.length - 1) {
            // 最后一个部分，不需要翻译
            currentLevel[part].key = line;
        } else {
            // 需要翻译的部分
            if (currentLevel[part].name === "") {
                currentLevel[part].name = String(ba);
                progressBar.tick();
                //console.clear();
            }
            currentLevel = currentLevel[part].sound;
        }
    }
}

// 读取文件并处理
async function readFileAndProcess() {
    const lines = fs.readFileSync(filePath, 'utf-8').split(/\r?\n/);
    progressBar.total = lines.length;

    for (const line of lines) {
        if (line) { // 忽略空行
            // 更新进度条的总数
            progressBar.total++;
            await processLine(line);
        }
    }

    // 写入文件
    fs.writeFileSync(outputPath, JSON.stringify(jsonOutput, null, 2), 'utf8');
    console.log(`翻译完成，已保存至JSON文件：${outputPath}`);
}

readFileAndProcess();
